package com.mybatis.jpa.statement.builder;

import com.mybatis.jpa.meta.MybatisColumnMeta;
import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;
import com.mybatis.jpa.statement.SqlAssistant;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 判空插入
 * @author wanglei
 * @date 2020 -02-06 11:06:32
 */
public class InsertSelectiveBuilder extends BaseInsertBuilder {

	@Override
	public String buildSQL(PersistentMeta persistentMeta, Method method) {
		// columns
		StringBuilder columns = new StringBuilder();
		columns.append("<trim prefix='(' suffix=')' suffixOverrides=',' > ");
		// values
		StringBuilder values = new StringBuilder();
		values.append("<trim prefix='(' suffix=')' suffixOverrides=',' > ");
		for (MybatisColumnMeta columnMeta : persistentMeta.getColumnMetaMap().values()) {
			if(columnMeta.isVersion())
			{
				columns.append(columnMeta.getColumnName() + ", ");
				values.append(0 + ", ");
				continue;
			}
			// columns
			columns.append("<if test='" + columnMeta.getProperty() + "!= null'> ");
			columns.append(columnMeta.getColumnName() + ", ");
			columns.append("</if> ");

			// values
			values.append("<if test='" + columnMeta.getProperty() + "!= null'> ");
			values.append(SqlAssistant.resolveSqlParameter(columnMeta) + ", ");
			values.append("</if> ");
		}

		columns.append("</trim> ");
		values.append("</trim> ");

		return "<script>" + "INSERT INTO " + persistentMeta.getTableNameFlag() + columns.toString() + " VALUES "
				+ values.toString() + "</script>";
	}

	@Override
	public void parseStatement(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method) {
		// 方法名
		adapter.setMethodName(method.getName());
		// 参数类型
		adapter.setParameterTypeClass(persistentMeta.getType());
		// sqlScript
		adapter.setSqlScript(buildSQL(persistentMeta, method));
		super.setKeyGenerator(adapter,persistentMeta,method);
		adapter.parseStatement();

	}

}
